- Special Edition Using Visual Basic Script -

CHAPTER 14 - Comparing Scripting Languages

by Tom Tessier


In this chapter, you learn about MicrosoftÆs implementation of the JavaScript language. It should be noted that JavaScript is not Java. While Java is a scaleable platform independent language requiring a Java compiler, JavaScript is a scripting language interpreted on-the-fly by a Web browser in much the same manner as VBScript. Developed by Netscape Communications Corporation, JavaScript (known as LiveScript during development) requires no compiler or development kits. In an attempt at compatibility with NetscapeÆs browser, Microsoft has included a JavaScript interpreter within Internet Explorer 3.0.

JavaScript is not Java. Although JavaScript has syntax and operators exactly the same as that of Java, the concept and capabilities of JavaScript are very different. A Web browser interprets JavaScript on-the-fly upon contact with a page containing the <SCRIPT LANGUAGE=öJavaScriptö> tag, whereas Java is first precompiled using the Java SDK and then the resulting bytecodes are placed on a Web server and referenced on a page via the <APP> HTML command. When a browser encounters this tag, it loads in the precompiled bytecodes and interprets these on-the-fly.

In essence, Java is half a compiled language and half an interpreted language, whereas JavaScript is entirely interpreted. Both JavaScript and Java resemble C++, without C++Æs nuisances such as memory leaks. Java is a distributed language, of considerably more power than JavaScript or even VBScript. Java is comparable to Visual Basic for Applications (OLE creator for use on Web pages) in power.

ON THE WEB

http://java.sun.com If you are interested in Java programming, download the latest free Java SDK from this site.

An Overview of JavaScript

If youÆve done any Java or C++ programming, youÆll be at home with JavaScript. Unlike C++, it is not necessary to include a ; symbol at the end of each code line, but for consistency with Java it is recommended. The C++ comments // comment text and /* comment text */ also pass over to JavaScript. To wrap a section of code down to the next line in JavaScript, use the backslash (\) character. Refer to Table 14.1 for a summary of these very basic JavaScript syntax commands and their VBScript counterparts.

As with VBScript, a JavaScript session is initiated via the <SCRIPT> command. However, instead of ôVBSö the Language parameter is set to either ôLiveScriptö or ôJavaScriptö (LiveScript was the previous name of JavaScript). The following JavaScript code demonstrates how to use the <SCRIPT> tag:

<SCRIPT Language=öJavaScriptö>

{

JavaScript code body here

}

</SCRIPT>

It should be noted that both JavaScript and VBScript are case sensitive. This means that the case of letters composing a name or object is importantùa variable named Myvar is entirely different than one written as myvar.

JavaScript Variables and Operators

As you probably know by now, some of the most basic instructions of any programming language are variable declarations and operators. These are used to set up numbers and text strings as well as to perform actions and comparisons which determine the outcome of a given program.

Variables

Variables are used to set up numbers and text strings for use later in a program. Variables in JavaScript are assigned exactly the same way as in VBScript. The variable name is on the left, and the corresponding data type literal is on the right. For example, to define an integer, a floating-point literal, a string, and a Boolean, one would write the following JavaScript program:

myint = 10;

mystring = ôJoe Moeö;

myfloat = 50.99;

myboolean = false;

The var command must be employed if you want to reuse a variable name inside of a function. For example, this JavaScript code changes the original value of the variable life to 299:

function lifetime()

{

life = 100;

changelife(); // call the changelife function

document.write (life+ô ö); // write the life variable to the page

}

function changelife()

{

life = 299; // change life variable to 299

// (changes the original variable)

document.write (life); // write the life variable

}

The page output is 299 299 (document.write is a built-in object which places text directly onto the HTML pageùsee the "JavaScript Objects" section for more information). Now, letÆs look at the same JavaScript example, this time using var to create a new instance of the life variable:

function lifetime()

{

life = 100;

changelife(); // call the changelife function

document.write (life+ô ö); // write the life variable to the page.. will

// be unchanged

}

function changelife()

{

var life = 299; // create a new instance of the life variable

// and initialize it to 299

document.write (life); // write this new life variable

}

The page output is 299 100. By using var, life is redeclared, hiding the previous definition in the code body. When the changelife function ends, the second life variable is destroyed and the original restored.

Variable and function names must begin with a letter or underscore character. The remaining characters can include digits (0û9) and upper- or lowercase letters. Remember, the case of such variable names is important (in both VBScript and JavaScript)ùa function named MyFunction99 is entirely different from one called myfuncTion99 (see "JavaScript Execution Flow and Functions" for more information on functions).

The available JavaScript data type literals available for equating to variable names are as follows:

When declaring a variable, note that its literal type is automatically determined at runtime by the browser. For example, n = 100 declares a variable of type integer. If, later on, n is assigned a floating-point literal, the browser automatically converts n to a floating-point variable.

Operators

Operators are used to perform actions and comparisons which determine the outcome of a given program section. For example, to add two numbers together, the JavaScript plus (+) operator is used:

a = b + c;

a is assigned the value of b plus c. To check if b is greater than c, one of the JavaScript compare (<, <=, >, or >=) operators must be used:

if ( b > c )

If b is greater than c, then the code contained in the if statement will activate (see "JavaScript Execution Flow and Functions" for more information on if statements).

Table 14.2 lists the various JavaScript operators and their corresponding VBScript counterparts.

Table 14.2 Comparison of JavaScript and VBScript Operators

Operation JavaScript Operator VBScript Operator

Mathematical Operators

Addition + +
Subtraction - -
Multiplication * *
Division / /
Divide and return an integer value N/A \
Exponentiation N/A ^
Modulus % MOD
Negation - -
String concatenation + + or &
Left shift << N/A
Right shift >> N/A
Bitwise AND & AND
Bitwise OR | OR
Bitwise XOR ^ XOR
Bitwise complement ~ NOT

Comparison Operators

Less than < <
Greater than > >
Less than or equal to <= <=
Greater than or equal to >= >=
Equal to == =
Not equal to != <>
Evaluation AND && AND
Evaluation OR || OR
Evaluation XOR N/A XOR

All of the preceding operators function exactly the same as their VBScript counterparts. For example, take a look at this JavaScript code:

a = b + c;

a = b & c;

The VBScript equivalent has the exact same structure:

a = b + c

a = b AND c;

For examples of JavaScript vs VBScript comparison operators, see the following section, or refer to Chapter 16, ôVBScript Operators.ö

JavaScript Execution Flow and Functions

JavaScriptÆs methods for directing execution flow, via decision and loop statements, are identical to those of C/C++.

Decision Statements

These control statements evaluate an expression, and then take an action based on whether the expression is true or false.

The if command executes one or more lines of code based on whether the expression in parentheses after the if statement is true. Note that expression makes use of the compare operators listed in the previous section, "JavaScript Operators." The following JavaScript program illustrates a typical if statement in action:

if ( (str == ôö) && (myval < min) || (myval > max) )

alert(ôStr is empty, and either myval is lessö+

ô than min or greater than maxö);

The JavaScript alert is only executed if the entire expression from left to right evaluates to true. In other words, the variable string str must be empty, and either myval less than min or myval greater than max for the expression to evaluate as true. Notice the use of the plus (+) operator to wrap the string over multiple lines.

In VBScript, no parentheses enclose the if expression(s). As well, the Then command must be placed at the end of the if line. Finally, an end if is placed at the end of the entire if structure (after the executable code). The following presents exactly how the if statement is used in VBScript:

if str = ôö AND myval < min OR myval > max Then

alert ôStr is empty, and either myval is lessö+

ô than min or greater than maxö

end if

More than one line can be included for execution after the if statement by enclosing the line in standard C/C++ brackets. The following JavaScript code illustrates this:

if (confirm(ôProceed?ö))

{

myval = min;

myval++;

}

If the results of the built-in JavaScript function confirm (which initiates a YES/NO dialog box) are true (YES selected), then the two lines enclosed in { } are executed. In VBScript, the brackets must not be used since the interpreter keeps reading in lines of code until an end if statement is encountered.

The else and else if commands are placed directly after if statements to select alternate code that executes when the if expression fails. else executes its alternate code every time, whereas the code contained in an else if statement only runs if its expression is true. For example, suppose one needed to perform three different actions, with only one action occurring at any given time based upon the value of certain variables. An if statement would be used to decide whether to perform the first action, an else if command to decide the second, and another else if statement (or simply else if this alternate code is to execute every time) for the third. The following JavaScript code illustrates the if...else concept:

if (aint < bint)

aint = bint;

else if (aint > bint)

{

aint = cint;

cint--;

}

else

aint++;

In the preceding example, aint is set to bint only when aint is less than bint, otherwise aint is set to cint if aint is greater than bint. If neither the (aint < bint) or (aint > bint) expressions are true, then aint is incremented. VBScript if...else coding conventions follow exactly the same structure as in JavaScript. The only difference is that VBScript uses elseif to represent JavaScriptÆs else if, and no { } brackets are used (an end if is simply placed at the end of the entire structure in VBScript). The following VBScript code is equivalent to the preceding JavaScript program:

if aint < bint Then

aint = bint

elseif aint > bint Then

aint = cint

cint = cint - 1;

else

aint = aint + 1

end if

It should be noted that it is possible to nest if...else statements within other if...else statements, as in the following JavaScript code snippet:

if (aint < bint)

{

if (aint < cint)

{

aint = cint;

cint++;

}

else

aint = bint;

}

The preceding example in VBScript follows:

if aint < bint Then

if aint < cint Then

aint = cint

cint = cint + 1

else

aint = bint

end if

end if

Loop Statements

Loop statements repeat an action over and over again until an expression evaluates to true or false.

The while loop executes a set of commands as long as the test expression in parentheses after the while statement evaluates to true. As in JavaScriptÆs if...else structure, { } brackets must enclose the repeatable code body of the while statement. The { } brackets are optional if the code body is composed of only one line. The below JavaScript program shows the while loop in action:

while ( aint < cint || aint < bint )

{

aint++;

bint--;

}

The preceding program executes the two lines over and over until aint = cint or aint = bint. Literally, while aint is less than cint or aint is less than bint, increment aint and decrement bint. What follows is the VBScript version of the above program:

while aint < cint OR aint < bint

aint = aint + 1

bint = bint - 1

wend

Note that for the while loop in VBScript, parenthesis are not needed around the conditional expression, no { } are used around the code body, and a wend statement terminates the repeatable code segment.

The for loopÆs structure is very similar to that of the while loop. Observe the for loop in the following JavaScript code:

for (var i = 0; i < 10; i++)

{

aint++;

bint=bint+10;

}

The for loop is decomposed as follows:

for (expression a; expression b; expression c)

Expression a is executed when the for loop begins. This is usually where one initializes the loop variables. While Expression b is true, the statements enclosed in the { } area execute. Upon reaching the last statement enclosed within the { } block, expression c runs and the loop repeats until expression b becomes true, upon which the loop ends. The equivalent VBScript code for the preceding for loop is listed below:

for i = 0 to 10 step 1

aint = aint + 1

bint = bint + 10

next

Again, no parentheses enclose the expression list in VBScript. As well, a next statement is used to indicate the end of the repeatable code body, in place of JavaScriptÆs { } commands. Observe that the step 1 VBScript keyword is optional in this case, since the step size (amount to increment i by) automatically defaults to one. Refer to Chapter 17, ôVBScript Control of Flow and Error Handling,ö for a complete explanation of VBScriptÆs flow control handling.

Functions

A function is a means of subdividing a program into smaller, easier to read code packets. Functions are also modular, in that they can be reused with ease from program to program. A function is usually passed a list of variables, performs actions based upon these variables, and then returns a value to the calling code. The calling code then performs subsequent actions based upon this returned value. JavaScript functions are defined using the function keyword, as follows:

function name(arguments)

{

code body of function

}

Name indicates the name of the function to use, while arguments represent the values or variables passed to the function for use in its code body. The return statement is used in the functionÆs code body to pass a value back to the calling code. The preceding function is called with the below JavaScript:

name(arguments);

Or, if the function is returning a needed value via the return statement, the function must be called with the equate (=) operator to assign the returned value to a variable. The below JavaScript code illustrates this:

function name(arguments)

{

code body of function

return value;

}

storevalue = name(arguments);

The variable storevalue is assigned the value returned by the name function.

VBScript, in contrast, defines functions using sub. Refer to the VBScript function layout shown below:

sub name(arguments)

code body of function

end sub

Notice the differences between JavaScript and VBScript. First of all, VBScript employs sub in place of JavaScriptÆs function. Secondly, VBScript uses end sub to terminate the function code body, instead of JavaScriptÆs enclosing { } brackets.

If function and end function are used in place of sub and end sub, the VBScript function is allowed to return a value. The below VBScript code illustrates how this is done:

function name(arguments)

code body of function

return name

end sub

Notice that in VBScript, the actual name of the function must be used after the return statement.

VBScript functions are called almost exactly the same way as in JavaScript. Refer to the below VBScript example:

name arguments

Notice that no parenthesis are used in the VBScript version of the function call. As in JavaScript, if the VBScript function is returning a value, the function must be called with the equate (=) operator to assign the returned value to a variable. The below VBScript shows this:

storevalue = name arguments

The variable storevalue is assigned the value returned by the name function (note that name must be declared using VBScriptÆs function and end function statements in order to return a value).

See Chapter 19, ôVBScript Procedures,ö for more information on VBScript subroutines and functions.

All functions should be placed between <HEAD><SCRIPT> and </SCRIPT></HEAD> tags, since the <HEAD> tag information is loaded first on a Web page. This ensures that no JavaScript or VBScript code attempts to call a function that has not been loaded yet.

Listing 14.1 and the resulting page shown in Figure 14.1 demonstrate JavaScript control flow and function calling in action. Listing 14.2 is the same program in VBScript. Listing 14.1 can be found on the CD-ROM in file LST18_1.HTM.

Listing 14.1 LST18_1.HTMùSample JavaScript Program Illustrating Control Flow and Function Calling

<SCRIPT Language="JavaScript">
function writepage(start_text, number_repetitions)
{
document.write ("<H1>"+start_text+"</H1><BR>");
for (j = 0; j < number_repetitions; j=j+2) // increment j by 2 each
// time through the loop
{
document.write ("J = "+j+"<BR>"); // write the value of j
// to the page
if (j == 10)
document.write ("<H2>Five times through</H2><BR>");
else if (j == 20)
document.write ("<H3>Ten times through</H3><BR>");
}
} // end of function writepage
// above function has not been executed up to this point...
writepage ("Greetings OB1. We meet again at last.",20);
// call the writepage function with "Greetings... for the first argument
// and 20 for the second argument
</SCRIPT>

FIG. 14.1

The resulting page generated both by the JavaScript in Listing 14.1 and the VBScript in Listing 14.2.

Listing 14.2 can be found on the CD-ROM in file LST18_2.HTM.

Listing 14.2 LST18_2.HTMùVBScript Equivalent of Listing 14.1

<SCRIPT Language="VBS">
sub writepage(start_text, number_repetitions)
document.write "<H1>" & start_text & "</H1><BR>"
for j = 0 to 18 step 2 ' increment j by two each
' time through the loop
document.write "J = " & j & "<BR>" ' write the value of J
' to the page
if j = 10 then
document.write "<H2>Five times through</H2><BR>"
elseif j = 20 then
document.write "<H3>Ten times through</H3><BR>"
end if
next
end sub ' end of function writepage
' above function has not been executed up to this point...
writepage "Greetings OB1. We meet again at last.",20
' call the writepage function with "Greetings... for the first
' argument and 20 for the second argument
</SCRIPT>

JavaScript Objects

JavaScript does not provide all of the features of a true Object Oriented Programming (OOP) language. Features such as encapsulation, inheritance, and abstraction are missing. It does in fact allow one to create and use objects that have methods (functions associated with an object) and properties (variables or attributes of an object). JavaScript has several built-in objects available for use. Some of these objects are quite similar to VBScriptÆs built-in functions.

Built-In Objects

VBScript has functions, whereas JavaScript has objects. These objects in turn have methods (functions associated with the object) and properties (variables associated with the object).

These JavaScript built-in objects are used very differently than the VBScript built-in functions. First of all, a property is an attribute or variable of an object while a method is a function associated with the object. In JavaScript, for example, one would use the following code to get the length of a string:

mystring = ôGreetingsö;

stringlength = mystring.length;

stringlength2 = ôGreetingsö.length;

where stringlength contains the same value as stringlength2. Notice that the string itself is treated as an object and the length is simply a property of this object. Observe that a period separates the object name on the left from the desired property on the right. The JavaScript convention, borrowed from C/C++ (which Java also uses), is to have the object name on the left, with the desired method (function) or property (variable) on the right (a dot separates the object on the left from the method or property on the right).

To perform similar actions in VBScript, built-in functions must be used. For example, to mimic the earlier JavaScript code that computed the length of a string, the VBScript len function must be employed as in the below VBScript program sample:

mystring = ôGreetingsö

stringlength = len(mystring)

stringlength2 = len(ôGreetingsö)

Notice that built-in VBScript functions must have parenthesis surrounding their arguments (as in len(mystring)).

In order to obtain a deeper understanding of the JavaScript objects in Table 14.5, each of them will now be examined in greater detail.

String Object

To access the string object, a string variable or literal must be used as the object name on the left, with the desired string object method (function) or property (variable) on the right (left and right separated by a dot again). For example, observe the toUpperCase() method in the below JavaScript:

newstring = oldstring.toUpperCase();

newstring is filled with the contents of oldstring (oldstringÆs contents are converted to uppercase first). The VBScript equivalent of the preceding line follows:

newstring = ucase(oldstring)

Properties are accessed the same way, as illustrated by the JavaScript string object example just after Table 14.5.

Math Object

In order to use any of the math properties and methods, the Math keyword (note the capital M) must precede all references to the math object. Refer to the following JavaScript code:

a = Math.cos (Math.PI/4);

b = Math.pow(3,5);

When run, the above program gives a = 0.70710678 and b = 243. Alternatively, the special JavaScript keyword with can be used to associate ALL references to a method or property to a given object. For example, using with on the Math object in the previous code gives the following new JavaScript:

with (Math)

{

a = cos (PI/4);

b = pow (3,5);

}

The VBScript version of the preceding code follows:

a = cos (3.14159/4)

b = 3^5

Note again that VBScript uses functions in place of JavaScriptÆs objects (the cos function, and the ^ ôfunctionö).

Window Object

The window object represents all properties and methods associated with the browser itself. This object allows access to the status bar, activates pop-up message windows, and so forth. It is not necessary to prefix any of the window objectÆs properties and methods with the window keyword. For example, look at the following JavaScript code:

window.alert (ôINTRUDER ALERT! INTRUDER ALERT!ö);

Instead of accessing the alert method (function) via window.alert, JavaScript allows alert alone to be used (since alert is a method of the window object). The below JavaScript code performs exactly the same function as in the previous example:

alert (ôINTRUDER ALERT! INTRUDER ALERT!ö);

The VBScript equivalent follows:

alert ôINTRUDER ALERT! INTRUDER ALERT!ö

The window keyword may also optionally be placed in front of the VBScript alert function, since the web browserÆs interpreter automatically removes any window. statements on-the-fly while going through the web page.

Location Object

The location object represents only the properties associated with the current document location/URL (http://www.solstar.com is an example of a URL, or Uniform Resource Locator). Having no methods, the location object is used to access and/or change the current page (URL) the document is pointing to. The JavaScript location objectÆs properties must be prefixed with the location keyword. Refer to the following JavaScript code:

location.href = ôhttp://www.url.comö;

The preceding example points the current page to http://www.url.com (in other words, the current page is lost, and the new page replaces it). Pointing the location.href to itself (location.href = location.href) causes the document to reloadùhowever, this only works in Netscape 2.0 and up (although the final release of Internet Explorer 3.0 may in fact support dynamic document reloads like Netscape 2.0). Notice from Table 14.5 that the VBScript equivalent of the JavaScript location.href object is exactly the same. The VBScript location.href is not actually an object, however. Instead, think of it as a global variable, built-into the VBScript language. So the VBScript version of the preceding JavaScript code is exactly the same, as illustrated below:

location.href = ôhttp://www.url.comö

Document Object

The document object represents all of the properties and methods associated with the actual HTML document itself. This object allows write access to the page, lets HTML form input areas be examined and/or changed, and so on. The properties and methods of the document object must be prefixed with the document keyword. For example, to write directly to the HTML page, use the write method (function) as illustrated by the following JavaScript:

document.write (ôWell good day to you too!!ö);

Note that one cannot use document.write AFTER the page has completely loaded and executed (ie: in an event, for exampleùsee the following JavaScript Event Programming section).

The VBScript function equivalent operates almost exactly the same way, as shown here:

document.write ôWell good day to you too!!ö

document.write is not an object in VBScript - think of it as a built-in function. Notice that this document.write function is called using standard VBScript function calling practices: no parenthesis must enclose the arguments.

When the web browser encounters a form defined in standard HTML code via the <FORM> tag, an array table is set up for use by JavaScript or VBScript. For each pair of <FORM> and </FORM> tags, a separate entry in the document.forms array object is created. To access individually named <INPUT> tags in these forms, append the desired <INPUT> itemÆs name and VALUE attribute to the document.forms object, as in the JavaScript in Listing 14.3. The output of Listing 14.3 is shown in Figure 14.2. Listing 18.3 can be found on the CD-ROM in file LST18_3.HTM.

Listing 14.3 LST18_3.HTMùJavaScript Program Illustrating document.forms[0] Array Object to Access Form Data

<HTML><BODY>
<FORM>
<INPUT TYPE="text" NAME="accessme">
</FORM>
</BODY></HTML>
<SCRIPT Language="JavaScript">
document.forms[0].accessme.value = "HIYA MON!";
</SCRIPT>

FIG. 14.2

The resulting page generated by the JavaScript in Listing 14.3.

The document.forms[0] array is indexing the first form in the document (form 0). As well, the object is reading the accessme form input and changing its value to the string ôHIYA MON!ö Notice the code that changes the form input must be placed after the definition of the accessme input, since the page is loaded into the browser from the top down. If the JavaScript document.forms[0].accessme.value code is placed above the actual form, no data can be entered into the form input: the <FORM> tag has not even been read in and defined at that point.

Forms can also be referenced by name instead of by array, as in the JavaScript in Listing 14.4. Listing 14.4 can be found on the CD-ROM in file LST18_4.HTM.

Listing 14.4 LST18_4.HTMùJavaScript Program Demonstrating Form Data Access via Form Names

<HTML><BODY>
<FORM NAME=öform_nameö>
<INPUT TYPE="text" NAME="accessme">
</FORM>
</BODY></HTML>
<SCRIPT Language="JavaScript">
document.form_name.accessme.value = "HIYA MON!";
</SCRIPT>

The JavaScript in Listing 14.5 shows that MicrosoftÆs Internet Explorer 3.0 Alpha 1 (4.70.1028) allows one to get away with not using a <FORM> tag in the JavaScript. Listing 14.5 can be found on the CD-ROM in file LST18_5.HTM.

Listing 14.5 LST18_5.HTMùJavaScript Program Showing Internet Explorer 3.0Æs Capability to Create and Access Form Data without the Need of <FORM> Tags

<HTML><BODY>
<INPUT TYPE="text" NAME="accessme">
</BODY></HTML>
<SCRIPT Language="JavaScript">
accessme.value = "HIYA MON!";
</SCRIPT>

The preceding JavaScript code is incompatible with the Netscape browser. The Netscape client requires that all input elements be placed within <FORM> and </FORM> tags.

As long as you can get used to treating form inputs as page outputs, the concept of the form object can be easily understood. Unlike the JavaScript in Listing 14.3, the forms[index] array property cannot be used to access VBScript form data. Instead, the actual form name must be used, as in the VBScript in Listing 14.6. Listing 14.6 can be found on the CD-ROM in file LST18_6.HTM.

Listing 14.6 LST18_6.HTMùVBScript Program Illustrating Form Access via Form Names

<HTML><BODY>
<FORM NAME=öform_nameö>
<INPUT TYPE="text" NAME="accessme">
</FORM>
</BODY></HTML>
<SCRIPT Language="VBS">
document.form_name.accessme.value = "HIYA MON!"
</SCRIPT>

For VBScript in Internet Explorer 3.0 Alpha 1 (4.70.1028), the <FORM> tag is not even necessary, as shown in the VBScript in Listing 14.7. Listing 14.7 can be found on the CD-ROM in file LST18_7.HTM.

Listing 14.7 LST18_7.HTMùVBScript Program Demonstrating Internet Explorer 3.0Æs Capability to Create and Access Form Data without the Need of <FORM> Tags

<HTML><BODY>
<INPUT TYPE="text" NAME="accessme">
</BODY></HTML>
<SCRIPT Language="VBS">
accessme.value = "HIYA MON!"
</SCRIPT>

In general, it is good practice to use the <FORM> tag around <INPUT> sections. That way the contents of the form can be submitted to a server for post processing, and converting the HTML/VBScript code to NetscapeÆs JavaScript implementation becomes trivial.

Creating Objects

In JavaScript, use the C++ new command to dynamically create an object. Unlike C++ (and like Java), these dynamically created objects do not need to be destroyed, as the interpreter does all construction and destruction on-the-fly. Although VBScript can assign an object reference to a variable or property (as in Set formvar = document.form_name), it canÆt actually create a new object as JavaScript does.

To create an object, first define a function for the new object, as illustrated by the following JavaScript code:

function myobject(arguments)

{

methods/properties of function

}

Then later in the program, use the new command to dynamically create a new instance of the object. The next JavaScript illustrates this:

newobject = new myobject(arguments);

Creating Properties and Methods for Objects

When in an object function, use the keyword this to refer to the current object. With this, object properties are easily created, as the following JavaScript shows:

function myobject(name, number)

{

this.name = name;

this.number = number;

}

An instance of the object must be created with new, as the following JavaScript demonstrates:

newobject = new myobject(ôMorphing Forkö,22)

The properties of this new object can then be accessed in the usual way (object on the left, period, property or method on the right). For example, to assign values to two variables named a and b, use the following JavaScript:

a = newobject.name;

b = newobject.number;

Where a = ôMorphing Forkö and b = 22 (these values were defined when newobject was created via the new command, shown earlier). To add a method to this object, simply point a property in the object definition to a function, as the this JavaScript code illustrates:

function myobject(name, number)

{

this.name = name;

this.number = number;

this.method_name = method_name;

}

function method_name()

{

code body of method

}

The methods of this new object are again accessed in the usual wayùobject on the left, period, method (function) on the right.

Creating an Array Object

As an example of object creation, the following creates an array object for use in your JavaScript:

function CreateArray(num)

{

this.length = n;

for (var i = 1; i <= n; i++)

{

this[i] = 0;

}

return this

}

This creates an array of num entries with a length property indicating the number of entries in the array. The array entries are initialized to zero upon creation. To make an array, use the object in JavaScript as follows:

array = new CreateArray(3);

array[1] = 3;

array[2] = 1;

lenarray = array.length;

Compared to JavaScript, making arrays in VBScript is easy. For example, the below VBScript uses the Dim statement in conjunction with Array to define an array:

Dim A

A = Array(3,1,2)

B = A(2)

lenarray = len(A)

JavaScript Event Programming

As in VBScript, JavaScript can be activated by events placed in ordinary HTML tags such as <INPUT> and <FORM>. These event tags work exactly the same as in VBScript, since JavaScript and VBScript share common HTML code. For example, what follows is the JavaScript HTML onChange handler to call a function when a form input named text_area changes:

<INPUT TYPE=ôtextö NAME=ôtext_areaö onChange=ôfunction(arguments)ö>

In VBScript HTML, the function is called without parenthesis as shown in this next line of code:

<INPUT TYPE=ôtextö NAME=ôtext_areaö onChange=ôfunction argumentsö>

It is also possible to place JavaScript code directly into the onEvent area, as shown in this line of code:

<INPUT TYPE=ôtextö NAME=ôtext_areaö onChange=ôalert(æDon\Æt touch that dial!Æ);ö>

Notice the use of the apostrophe (æ) character within the alert. This serves to prevent the interpreter from confusing the start of the alert text with the end of the onChange event (which must be enclosed in quotation marks). Also, a \Æ character is used to create the apostrophe for the donÆt text, since it would be confused with a closing apostrophe otherwise.

VBScript code can also be used in an onEvent, as the following example illustrates:

<INPUT TYPE=ôtextö NAME=ôtext_areaö onChange=ôalert æDon\Æt touch that dial!Æ ö>

The browser automatically determines which language (VBScript or JavaScript) to use in onEventÆs, based upon what was previously implemented in the same file. Beware of mixing JavaScript and VBScript code within the one fileùthis crashes Internet Explorer 3.0 (when Explorer 3.0 encounters an onEvent containing a language different from what was used before in previous <SCRIPT> tags, a runtime error is generated).

As of this writing, the current version of Internet Explorer 3.0 is Alpha 1 (4.70.1028). This version does not function properly with the onSelect, onMouseOver, and onSubmit event handlers. JavaScript code using these events under Netscape 2.0 or higher works just fine, however. Refer to Chapter 18, ôVBScript Event Programming,ö for more information on using events in VBScript.

Putting It All Together

Using all of the basic techniques learned so far, you now have the ability to create real world JavaScript applications. At the very least, you should be able to convert existing VBScript applications to JavaScript (to guarantee your web pageÆs compatibility with Netscape 2.0 as well as Internet Explorer 3.0). The JavaScript found in Listing 14.8 and the VBScript equivalent in Listing 14.9 (both listings are too large to print entirely here, the full versions can be found on the CD) generate the page shown in Figure 14.3. The complete Listing 14.9 can be found on the CD-ROM in file LST18_9.HTM.

This type of page is the perfect example of a typical real world JavaScript and VBScript Web page. The program makes use of HTML tables extensively to create an order form, and employs all of the concepts IÆve discussed so far, as well as those mentioned throughout the rest of this book. Refer to Chapter 2, "Review of HTML," for more examples of table usage. The complete Listing 14.8 can be found on the CD-ROM in file LST18_8.HTM.

ON THE WEB

http://www.stars.com/Tutorial/HTML/Tables Check out this site for more examples of table usage.

http://www.w3.org/pub/WWW/MarkUp/Tables/950915_tables.html This site contains the HTML 3.0 draft specification of the table model.

Listing 14.8 LST18_8.HTMùReal World JavaScript Program: Calculates the Total Price Based on User Selections

<HTML>
<HEAD>
<SCRIPT Language="JavaScript">
// below variables automatically globalized since they are not defined inside
// any functions - ie: these variables will be remembered each time through
// the updateprice function
old_p_price=0; // initialize variables to 0
old_d_price=0;
old_v_price=0;
old_m_price=0;
old_o_price=0;
old_c_price=0;
subtotal_price=0;
function updateprice (who_called, chosen)
{
// processor price data
p0 = 2000; // P166
p1 = 1800; // P150
p2 = 1500; // P133
p3 = 1300; // P120
p4 = 1100; // P100
p5 = 900; // P90
p6 = 600; // P75
p7 = 425; // P66
p8 = 300; // P60
.
.
.
// point to subtotal form input
form_subtotal = document.computer.subtotal;
if (who_called == 0) // clicked on Processor area?
{
// point to processor price form input
curItem = document.computer.processor_price;
if (chosen == 0) // P166?
{
curItem.value = "$"+p0;
new_prev_price = p0;
}
else if (chosen == 1) // P150?
{
curItem.value = "$"+p1;
new_prev_price = p1;
}
else if (chosen == 2) // P133?
{
curItem.value = "$"+p2;
new_prev_price = p2;
}
else if (chosen == 3) // P120?
{
curItem.value = "$"+p3;
new_prev_price = p3;
}
else if (chosen == 4) // P100?
{
curItem.value = "$"+p4;
new_prev_price = p4;
}
else if (chosen == 5) // P90?
{
curItem.value = "$"+p5;
new_prev_price = p5;
}
else if (chosen == 6) // P75?
{
curItem.value = "$"+p6;
new_prev_price = p6;
}
else if (chosen == 7) // P66?
{
curItem.value = "$"+p7;
new_prev_price = p7;
}
else if (chosen == 8) // P60?
{
curItem.value = "$"+p8;
new_prev_price = p8;
}
// subtract the old processor price from the subtotal
subtotal_price = subtotal_price - old_p_price;
// and set the old processor price to the newly
// selected processor price
old_p_price = new_prev_price;
// and add the new processor price to the subtotal
subtotal_price = subtotal_price + new_prev_price;
// and set the subtotal form input to the subtotal price
form_subtotal.value = "$"+subtotal_price;
}
.
.
.
// compute the shipping value (0.1 * the subtotal_price)
document.computer.shipping.value = "$"+(0.1 * subtotal_price);
// and compute the total amount owed (the subtotal_price + the
// shipping value)
document.computer.total.value = "$"+
(subtotal_price + 0.1 * subtotal_price);
}
</SCRIPT>
</HEAD>
<BODY>
<FORM NAME="computer">
<TABLE BORDER=1 BGCOLOR="#FFFFCC" WIDTH=80 ALIGN=LEFT>
<FONT SIZE=2 COLOR=BLUE>
<TR><TD BGCOLOR=WHITE ALIGN=CENTER>Processor...</TD></TR></FONT>
<TR><TD>
<!-- when P166 is clicked on, call updateprice with arguments 0 and 0 -->
<INPUT TYPE=RADIO NAME=processor onClick="updateprice(0,0)"> P166
</TD></TR>
<TR><TD>
<!-- when P150 is clicked, call updateprice with arguments 0 and 1 -->
<INPUT TYPE=RADIO NAME=processor onClick="updateprice(0,1)"> P150
</TD></TR>
<TR><TD>
<INPUT TYPE=RADIO NAME=processor onClick="updateprice(0,2)"> P133
</TD></TR>
<TR><TD>
<INPUT TYPE=RADIO NAME=processor onClick="updateprice(0,3)"> P120
</TD></TR>
<TR><TD>
<INPUT TYPE=RADIO NAME=processor onClick="updateprice(0,4)"> P100
</TD></TR>
<TR><TD>
<INPUT TYPE=RADIO NAME=processor onClick="updateprice(0,5)"> P90
</TD></TR>
<TR><TD>
<INPUT TYPE=RADIO NAME=processor onClick="updateprice(0,6)"> P75
</TD></TR>
<TR><TD>
<INPUT TYPE=RADIO NAME=processor onClick="updateprice(0,7)"> P66
</TD></TR>
<TR><TD>
<INPUT TYPE=RADIO NAME=processor onClick="updateprice(0,8)"> P60
</TD></TR>
<TR><TD>
<INPUT TYPE=TEXT NAME=processor_price SIZE=11 VALUE="$0.00">
</TD></TR>
</TABLE>
.
.
.
<BR><BR><BR><BR><BR><BR><BR><BR><BR><BR><BR>
<TABLE BORDER=1 BGCOLOR="#FFFFCC" WIDTH=530 HEIGHT=90 ALIGN=LEFT>
<TR><TD>
Subtotal
</TD></TR>
<TR><TD>
Shipping Charges (please allow 4-6 weeks for delivery)
</TD></TR>
<TR><TD>
Total
</TD></TR>
</TABLE>
<!-- form inputs who's values are changed by the JavaScript code,
depending on the selections the user has made in regards to
processor type, monitor, memory, and so forth -->
<TABLE BORDER=1 BGCOLOR="#FFFFCC" WIDTH=70>
<TR><TD>
<INPUT TYPE=TEXT NAME=subtotal SIZE=10 VALUE="$0.00">
</TD></TR>
<TR><TD>
<INPUT TYPE=TEXT NAME=shipping SIZE=10 VALUE="$0.00">
</TD></TR>
<TR><TD>
<INPUT TYPE=TEXT NAME=total SIZE=10 VALUE="$0.00">
</TD></TR>
</TABLE>
<BR>
<INPUT TYPE=SUBMIT VALUE="Order now">
<A HREF="index.html">Return to main page</A>
</FORM>
</BODY>
</HTML>

FIG. 14.3

The resulting computer pricing page generated both by the JavaScript in Listing 14.8 and the VBScript in Listing 14.9.

The complete Listing 14.9 can be found on the CD-ROM in file LST18_9.HTM.

Listing 19.9 LST18_9.HTMùVBScript Equivalent of Listing 14.8

<HTML>
<HEAD>
<SCRIPT Language="VBS">
' use Dim to indicate that these variables are to be remember each time
' through the updateprice subroutine - ie: to GLOBALIZE the below variables
Dim old_p_price ' old processor price (integer)
Dim old_d_price ' old drive price (integer)
Dim old_v_price ' old video price (integer)
Dim old_m_price ' old memory price (integer)
Dim old_o_price ' old os price (integer)
Dim old_c_price ' old case price (integer)
Dim subtotal_price ' subtotal price (integer)
old_p_price=0 ' initialize variables to 0
old_d_price=0
old_v_price=0
old_m_price=0
old_o_price=0
old_c_price=0
subtotal_price=0
sub updateprice (who_called, chosen)
Dim form_subtotal
Dim curItem
' processor price data
p0 = 2000 ' P166
p1 = 1800 ' P150
p2 = 1500 ' P133
p3 = 1300 ' P120
p4 = 1100 ' P100
p5 = 900 ' P90
p6 = 600 ' P75
p7 = 425 ' P66
p8 = 300 ' P60
.
.
.
' point to subtotal form input
Set form_subtotal = document.computer.subtotal
if who_called = 0 Then ' clicked on Processor area?
' point to processor price form input
Set curItem = document.computer.processor_price
if chosen = 0 Then ' P166?
curItem.value = "$" & p0
new_prev_price = p0
elseif chosen = 1 Then ' P150?
curItem.value = "$" & p1
new_prev_price = p1
elseif chosen = 2 Then ' P133?
curItem.value = "$" & p2
new_prev_price = p2
elseif chosen = 3 Then ' P120?
curItem.value = "$" & p3
new_prev_price = p3
elseif chosen = 4 Then ' P100?
curItem.value = "$" & p4
new_prev_price = p4
elseif chosen = 5 Then ' P90?
curItem.value = "$" & p5
new_prev_price = p5
elseif chosen = 6 Then ' P75?
curItem.value = "$" & p6
new_prev_price = p6
elseif chosen = 7 Then ' P66?
curItem.value = "$" & p7
new_prev_price = p7
elseif chosen = 8 Then ' P60?
curItem.value = "$" & p8
new_prev_price = p8
end if
' subtract the old processor price from the subtotal
subtotal_price = subtotal_price - old_p_price
' and set the old processor price to the newly
' selected processor price
old_p_price = new_prev_price
' and add the new processor price to the subtotal
subtotal_price = subtotal_price + new_prev_price
' and set the subtotal form input to the subtotal price
form_subtotal.value = "$" & subtotal_price
.
.
.
' compute the shipping value (0.1 * the subtotal_price)
document.computer.shipping.value = "$" & (0.1 * subtotal_price)
' and compute the total amount owed (the subtotal_price + the
' shipping value)
document.computer.total.value = "$" &
(subtotal_price + 0.1 * subtotal_price)
end sub
</SCRIPT>
</HEAD>
<BODY>
<FORM NAME="computer">
<TABLE BORDER=1 BGCOLOR="#FFFFCC" WIDTH=80 ALIGN=LEFT>
<FONT SIZE=2 COLOR=BLUE>
<TR><TD BGCOLOR=WHITE ALIGN=CENTER>Processor...</TD></TR></FONT>
<TR><TD>
<!-- when P166 is clicked on, call updateprice with arguments 0 and 0 -->
<INPUT TYPE=RADIO NAME=processor onClick="updateprice 0,0"> P166
</TD></TR>
<TR><TD>
<!-- when P150 is clicked on, call updateprice with arguments 0 and 1 -->
<INPUT TYPE=RADIO NAME=processor onClick="updateprice 0,1"> P150
</TD></TR>
<TR><TD>
<INPUT TYPE=RADIO NAME=processor onClick="updateprice 0,2"> P133
</TD></TR>
<TR><TD>
<INPUT TYPE=RADIO NAME=processor onClick="updateprice 0,3"> P120
</TD></TR>
<TR><TD>
<INPUT TYPE=RADIO NAME=processor onClick="updateprice 0,4"> P100
</TD></TR>
<TR><TD>
<INPUT TYPE=RADIO NAME=processor onClick="updateprice 0,5"> P90
</TD></TR>
<TR><TD>
<INPUT TYPE=RADIO NAME=processor onClick="updateprice 0,6"> P75
</TD></TR>
<TR><TD>
<INPUT TYPE=RADIO NAME=processor onClick="updateprice 0,7"> P66
</TD></TR>
<TR><TD>
<INPUT TYPE=RADIO NAME=processor onClick="updateprice 0,8"> P60
</TD></TR>
<TR><TD>
<INPUT TYPE=TEXT NAME=processor_price SIZE=11 VALUE="$0.00">
</TD></TR>
</TABLE>
.
.
.
<BR><BR><BR><BR><BR><BR><BR><BR><BR><BR><BR>
<TABLE BORDER=1 BGCOLOR="#FFFFCC" WIDTH=530 HEIGHT=90 ALIGN=LEFT>
<TR><TD>
Subtotal
</TD></TR>
<TR><TD>
Shipping Charges (please allow 4-6 weeks for delivery)
</TD></TR>
<TR><TD>
Total
</TD></TR>
</TABLE>
<!-- form inputs who's values are changed by the VBScript code,
depending on the selections the user has made in regards to
processor type, monitor, memory, and so forth -->
<TABLE BORDER=1 BGCOLOR="#FFFFCC" WIDTH=70>
<TR><TD>
<INPUT TYPE=TEXT NAME=subtotal SIZE=10 VALUE="$0.00">
</TD></TR>
<TR><TD>
<INPUT TYPE=TEXT NAME=shipping SIZE=10 VALUE="$0.00">
</TD></TR>
<TR><TD>
<INPUT TYPE=TEXT NAME=total SIZE=10 VALUE="$0.00">
</TD></TR>
</TABLE>
<BR>
<INPUT TYPE=SUBMIT VALUE="Order now">
<A HREF="index.html">Return to main page</A>
</FORM>
</BODY>
</HTML>

From Here...

This concludes your crash course in JavaScript. Perhaps in a later release, Netscape will include VBScript support in its interpreter. Until then, if you want to create script pages compatible with both Netscape 2.0 and Internet Explorer 3.0, JavaScript is the way to go. VBScript is perhaps inherently more powerful with its capability to dynamically alter the behavior of Java and OLE objects (via the <OBJECT> tag), whereas Netscape 2.0 cannot yet read in a Microsoft OLE object (NetScape works great with Java, however). I wouldnÆt be surprised if Netscape Communications soon incorporated VBScript into its Netscape browser. So in the end, it probably doesnÆt really matter which scripting language you use: all browsers will be able to read all scripts.

For more information on JavaScript and VBScript, go to the following sites and chapters.

ON THE WEB

http://home.netscape.com/eng/mozilla/Gold/handbook/javascript/index.html Refer to this site for NetScapeÆs JavaScript Authoring Guide.

http://www.c2.org/~andreww/javascript This site contains an index of various JavaScript pages on the web plus JavaScript source code.


| Previous Chapter | Next Chapter |

| Search | Table of Contents | Book Home Page | Buy This Book |

| Que Home Page | Digital Bookshelf | Disclaimer |


To order books from QUE, call us at 800-716-0044 or 317-361-5400.

For comments or technical support for our books and software, select Talk to Us.

© 1996, QUE Corporation, an imprint of Macmillan Publishing USA, a Simon and Schuster Company.